﻿using AlibabaCloud.SDK.VIAPI.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AliYun_RenLian_Obj
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static DataTable GetDataSet(string safeSql)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
            try
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand(safeSql, con);
                cmd.CommandTimeout = 3000;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("连接超时时间已到"))
                {
                    MessageBox.Show("连接服务器超时！", "提示");
                    return null;
                }
                else
                {
                    throw ex;
                }

            }
            finally
            {
                if (con != null && con.State == System.Data.ConnectionState.Open)
                {
                    con.Close();
                }
                else if (con != null && con.State == System.Data.ConnectionState.Broken)
                {
                    con.Close();
                }
            }
        }

        public string z_url(string profile_picture, string HYBH)
        {
            try
            {
                string OSS_AccessKeyId = System.Configuration.ConfigurationManager.ConnectionStrings["RenLian_AccessKeyId"].ConnectionString.ToString();
                string OSS_AccessKeySecret = System.Configuration.ConfigurationManager.ConnectionStrings["RenLian_AccessKeySecret"].ConnectionString.ToString();

                // 场景一，使用本地文件
                string file = ConvertBase64ToImageAndSave(profile_picture, HYBH);
                // 场景二，使用任意可访问的url
                //string file = "https://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024";
                // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
                // 如果您用的是RAM用户的AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html。
                // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
                FileUtils fileobj = FileUtils.getInstance(Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                //FileUtils fileobj = FileUtils.getInstance(OSS_AccessKeyId, OSS_AccessKeySecret);
                string ossUrl = fileobj.Upload(file);
                //return ossUrl;
                return ossUrl;
            }
            catch (Exception)
            {
                return "";
            }

        }
        /// <summary>
        /// 将Base64字符串转换为PNG图片并保存到当前项目的Debug目录下
        /// </summary>
        /// <param name="base64String">Base64编码的图片字符串</param>
        /// <param name="fileName">保存的图片名称（自动添加.png扩展名）</param>
        /// <returns>保存后的图片完整路径，如果出错则返回null</returns>
        public static string ConvertBase64ToImageAndSave(string base64String, string fileName)
        {
            try
            {
                // 检查输入是否为空
                if (string.IsNullOrEmpty(base64String))
                {
                    throw new ArgumentNullException(nameof(base64String), "Base64字符串不能为空");
                }

                if (string.IsNullOrEmpty(fileName))
                {
                    throw new ArgumentNullException(nameof(fileName), "文件名不能为空");
                }

                // 处理可能包含的Data URI前缀
                if (base64String.StartsWith("data:image", StringComparison.OrdinalIgnoreCase))
                {
                    int commaIndex = base64String.IndexOf(',');
                    if (commaIndex > 0)
                    {
                        base64String = base64String.Substring(commaIndex + 1);
                    }
                }

                // 转换Base64字符串为字节数组
                byte[] imageBytes = Convert.FromBase64String(base64String);

                // 获取当前项目的Debug目录路径
                string debugDirectory = AppDomain.CurrentDomain.BaseDirectory;

                // 确保文件名有.png扩展名
                if (!fileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                {
                    fileName = Path.ChangeExtension(fileName, ".png");
                }

                // 组合完整的文件路径
                string filePath = Path.Combine(debugDirectory, fileName);

                // 保存图片为PNG格式
                using (MemoryStream ms = new MemoryStream(imageBytes))
                {
                    using (Image image = Image.FromStream(ms))
                    {
                        image.Save(filePath, ImageFormat.Png);
                    }
                }

                return filePath;
            }
            catch (FormatException)
            {
                Console.WriteLine("错误: 无效的Base64格式");
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"转换过程中发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 执行增删改语句
        /// </summary> 
        /// <param name="tablename"></param>
        public static void Updatedata(string sql)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
            con.Open();
            //SqlConnection con = COMMON.Con;
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = sql;
            SqlDataReader dr = com.ExecuteReader();//执行SQL语句
            dr.Close();
            con.Close();
        }
        /// <summary>
        /// 删除当前应用程序Debug目录下的所有PNG图片文件
        /// </summary>
        /// <param name="includeSubdirectories">是否递归删除子目录中的PNG文件，默认为false</param>
        /// <returns>删除的文件数量</returns>
        /// <exception cref="UnauthorizedAccessException">没有权限访问文件或目录</exception>
        /// <exception cref="DirectoryNotFoundException">指定的目录不存在</exception>
        /// <exception cref="IOException">发生I/O错误，如磁盘已满</exception>
        public static int DeletePngFilesInDebugPath(bool includeSubdirectories = false)
        {
            // 获取当前应用程序的运行目录（通常是bin\Debug）
            string debugPath = AppDomain.CurrentDomain.BaseDirectory;
            return DeletePngFilesInDirectory(debugPath, includeSubdirectories);
        }

        /// <summary>
        /// 删除指定目录下的所有PNG图片文件
        /// </summary>
        /// <param name="directoryPath">要删除PNG文件的目录路径</param>
        /// <param name="includeSubdirectories">是否递归删除子目录中的PNG文件，默认为false</param>
        /// <returns>删除的文件数量</returns>
        /// <exception cref="UnauthorizedAccessException">没有权限访问文件或目录</exception>
        /// <exception cref="DirectoryNotFoundException">指定的目录不存在</exception>
        /// <exception cref="IOException">发生I/O错误，如磁盘已满</exception>
        public static int DeletePngFilesInDirectory(string directoryPath, bool includeSubdirectories = false)
        {
            if (!Directory.Exists(directoryPath))
            {
                throw new DirectoryNotFoundException($"指定的目录不存在: {directoryPath}");
            }

            int deletedCount = 0;
            SearchOption searchOption = includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

            try
            {
                // 获取所有PNG文件
                string[] pngFiles = Directory.GetFiles(directoryPath, "*.png", searchOption);

                // 逐个删除文件
                foreach (string filePath in pngFiles)
                {
                    try
                    {
                        File.Delete(filePath);
                        deletedCount++;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Console.WriteLine($"警告: 没有权限删除文件 {filePath}");
                    }
                    catch (IOException ex)
                    {
                        Console.WriteLine($"警告: 删除文件 {filePath} 时发生I/O错误: {ex.Message}");
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine($"错误: 没有权限访问目录 {directoryPath}");
                throw;
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine($"错误: 目录 {directoryPath} 不存在");
                throw;
            }
            catch (IOException ex)
            {
                Console.WriteLine($"错误: 访问目录 {directoryPath} 时发生I/O错误: {ex.Message}");
                throw;
            }

            return deletedCount;
        }
        private void Form1_Shown(object sender, EventArgs e)
        {
            try
            {

                DeletePngFilesInDebugPath();
            }
            catch (Exception ex)
            {

            }
            try
            {
                //Sample_DuanXin sample_DuanXin=new Sample_DuanXin();
                //sample_DuanXin.Main2("蒙B816WD");
                string RenLianDb_Name = System.Configuration.ConfigurationManager.ConnectionStrings["RenLianDb_Name"].ConnectionString.ToString();
                string QualityScoreThreshold = System.Configuration.ConfigurationManager.ConnectionStrings["QualityScoreThreshold"].ConnectionString.ToString();
                string SimilarityScoreThresholdInEntity = System.Configuration.ConfigurationManager.ConnectionStrings["SimilarityScoreThresholdInEntity"].ConnectionString.ToString();
                string SimilarityScoreThresholdBetweenEntity = System.Configuration.ConfigurationManager.ConnectionStrings["SimilarityScoreThresholdBetweenEntity"].ConnectionString.ToString();

                //DataTable dt_HYXXB_YB = GetDataSet("  select * from HYXXB where IS_YB<>'是' AND ISNULL(profile_picture,'')!='' ");
                //string str_sql = "";
                //for (int i = 0; i < dt_HYXXB_YB.Rows.Count; i++)
                //{
                //    string profile_picture = dt_HYXXB_YB.Rows[i]["profile_picture"].ToString().Trim();
                //    string HYBH = dt_HYXXB_YB.Rows[i]["HYBH"].ToString().Trim();
                //    string HYXM = dt_HYXXB_YB.Rows[i]["HYXM"].ToString().Trim();
                //    Sample_Add_RenLian_YangBen sample_Add_RenLian_YangBen = new Sample_Add_RenLian_YangBen();
                   
                //    var res_data_yb = sample_Add_RenLian_YangBen.Main2(RenLianDb_Name, HYBH, HYXM);
                //    if (res_data_yb.code == 1)
                //    {
                //        str_sql += " update HYXXB set IS_YB='是' where HYBH='" + HYBH + "'; ";
                //    }
                //}

                //DataTable dt_HYXXB_RL = GetDataSet("  select * from HYXXB where  IS_RL<>'是' AND ISNULL(profile_picture,'')!='' ");
         
                //for (int i = 0; i < dt_HYXXB_RL.Rows.Count; i++)
                //{
                //    string profile_picture = dt_HYXXB_RL.Rows[i]["profile_picture"].ToString().Trim();
                //    string HYBH = dt_HYXXB_RL.Rows[i]["HYBH"].ToString().Trim();
                //    string HYXM = dt_HYXXB_RL.Rows[i]["HYXM"].ToString().Trim();
                //    Sample_Add_RenLian sample_Add_RenLian = new Sample_Add_RenLian();
                //    string http_url = z_url(profile_picture, HYBH);
                //    var res_data_rl = sample_Add_RenLian.Main2(RenLianDb_Name, HYBH, HYXM, QualityScoreThreshold, SimilarityScoreThresholdInEntity, SimilarityScoreThresholdBetweenEntity, http_url);
                //    if (res_data_rl.code == 1)
                //    {
                //        str_sql += " update HYXXB set IS_RL='是' where HYBH='" + HYBH + "'; ";
                //        //
                //    }
                //}
                //Updatedata(str_sql);
            }
            catch (Exception)
            {

            }


            DataTable dt = GetDataSet("  select  * from clzc ");

            int X = 20;
            int Y = 30;
            int count = 1;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string clbhk = dt.Rows[i]["clbh"].ToString().Trim();
                string setclmc = dt.Rows[i]["setclmc"].ToString().Trim();
                string km = dt.Rows[i]["km"].ToString().Trim();
                string CID = dt.Rows[i]["CID"].ToString().Trim();
                string DID = dt.Rows[i]["DID"].ToString().Trim();
                string wldz = dt.Rows[i]["wldz"].ToString().Trim();
                string lch = dt.Rows[i]["lch"].ToString().Trim();
                Ren_LianModel frm = new Ren_LianModel(this, clbhk, setclmc, km, wldz, CID, DID, lch);

                frm.Name = "";
                frm.Location = new Point(X, Y);
                frm.BorderStyle = BorderStyle.FixedSingle;
                frm.Width = 513;
                frm.Height = 459;
                this.panel1.Controls.Add(frm);
                X += 533;
                if ((i + 1) % 3 == 0 && i != 0)
                {
                    X = 20;
                    Y += 479;
                }
                count++;
            }
            if (count == 1)
            {
                return;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
